package com.example.bbs.service.impl;

import com.example.bbs.entity.Disease;
import com.example.bbs.mapper.CommentMapper;
import com.example.bbs.mapper.DiseaseMapper;
import com.example.bbs.util.RedisUtil;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Set;

/**
 * @author jiajiazi
 * @version 1.0
 * @date 2021/6/28 13:40
 */
@Service
public class Quartzservice extends QuartzJobBean {
    @Autowired
    private DiseaseServiceImpl diseaseService;
    @Autowired
    private DiseaseMapper diseaseMapper;
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        System.out.println("redis update -- " + new Date());
        Set<String> keys = redisTemplate.keys("view_*");
        for (String key : keys) {
            int view = Integer.parseInt(String.valueOf(redisTemplate.opsForValue().get(key)));
            int id = Integer.parseInt(key.split("_")[1]);
            Disease disease = diseaseMapper.selectById(id);
            disease.setView(disease.getView() + view);
            System.out.println("更细view： id=" + id + "  view: " + disease.getView());
            diseaseMapper.updateById(disease);
            redisTemplate.delete(key);
        }
        Set<String> keys2 = redisTemplate.keys("comment_*");
        for (String key : keys2) {
            int value = Integer.parseInt(String.valueOf(redisTemplate.opsForValue().get(key)));
            int commentid = Integer.parseInt(key.split("_")[1]);
            System.out.println("更细comment： id=" + commentid + "  value: " + value);
            commentMapper.updateSupportById(commentid, value);
            redisTemplate.delete(key);
        }
    }
}
